/**
 */
package com.dingpeikeji.quickdeer.core.modules.returnrule.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dingpeikeji.quickdeer.core.common.persistence.Page;
import com.dingpeikeji.quickdeer.core.common.service.CrudService;
import com.dingpeikeji.quickdeer.core.common.utils.StringUtils;
import com.dingpeikeji.quickdeer.core.modules.returnrule.dao.TReturnruleDao;
import com.dingpeikeji.quickdeer.core.modules.returnrule.dao.TReturnruleDtlDao;
import com.dingpeikeji.quickdeer.core.modules.returnrule.entity.TReturnrule;
import com.dingpeikeji.quickdeer.core.modules.returnrule.entity.TReturnruleDtl;

/**
 * 退票规则定义Service
 * @author lh
 * @version 2016-07-08
 */
@Service
@Transactional(readOnly = true)
public class TReturnruleService extends CrudService<TReturnruleDao, TReturnrule> {

	@Autowired
	private TReturnruleDtlDao tReturnruleDtlDao;
	
	public TReturnrule get(String id) {
		TReturnrule tReturnrule = super.get(id);
		tReturnrule.settReturnruleDtlList(tReturnruleDtlDao.findList(new TReturnruleDtl(tReturnrule)));
		return tReturnrule;
	}
	
	public List<TReturnrule> findList(TReturnrule tReturnrule) {
		return super.findList(tReturnrule);
	}
	
	public Page<TReturnrule> findPage(Page<TReturnrule> page, TReturnrule tReturnrule) {
		return super.findPage(page, tReturnrule);
	}
	
	@Transactional(readOnly = false)
	public void save(TReturnrule tReturnrule) {
		int order = 0;
		
		if(tReturnrule.getReturnid()==null){
			dao.insert(tReturnrule);
		} else {
			dao.update(tReturnrule);
		}
		for (TReturnruleDtl tReturnruleDtl : tReturnrule.gettReturnruleDtlList()){
			if (TReturnruleDtl.DEL_FLAG_NORMAL.equals(tReturnruleDtl.getDelFlag())){
				order ++;
				tReturnruleDtl.setRtnorder(order);
				if (tReturnruleDtl.getRtndtlid() == null){
					tReturnruleDtl.setReturnid(tReturnrule);
					tReturnruleDtlDao.insert(tReturnruleDtl);
				}else{
					tReturnruleDtlDao.update(tReturnruleDtl);
				}
			}else if(tReturnruleDtl.getRtndtlid()!= null){
				tReturnruleDtlDao.delete(tReturnruleDtl);
			}
		}
	}
	
	@Transactional(readOnly = false)
	public void delete(TReturnrule tReturnrule) {
		/*super.delete(tReturnrule);
		tReturnruleDtlDao.delete(new TReturnruleDtl(tReturnrule));*/
		TReturnrule returnrule = new TReturnrule();
		returnrule.setReturnid(tReturnrule.getReturnid());
		super.delete(returnrule);
	}
	
	/**
	 * 根据退票规则名称获取退票规则
	 * @param rtnrulename
	 * @return
	 */
	public TReturnrule getReturnruleByRtnrulename(String rtnrulename) {
		return dao.findReturnruleByRtnrulename(rtnrulename);
	}
}
